#!/usr/bin/env python
# encoding: utf-8
'''
@author: zhaowenpeng
@contact: winston@peipeiyun.com
@software: garner
@file: auth.py
@time: 2020/6/2 3:43 下午
@desc:
'''

from functools import wraps
import logging
import traceback
from sanic.response import json

def check_authorization(request):
    '''校验cookie'''
    flag = False
    try:
        token = request.headers.get('token', '').strip()
        if token:
            AUTH_TOKEN = request.app.config['AUTH_TOKEN']
            cookies = request.app.get_auth_cookies(AUTH_TOKEN, token)
            flag = True
            # if cookies.get('validate',0)<int(time.time()):
            #     flag=False
    except:
        logging.error(traceback.format_exc())
        flag = False
    return flag

def authorized(f):
    @wraps(f)
    async def decorated_function(request, *args, **kwargs):
        is_authorized = check_authorization(request)
        if is_authorized:
            resp = await f(request, *args, **kwargs)
            return resp
        else:
            return json({'code': 203, 'info': '请登录'})
    return decorated_function
